
import time
import copy

import dexen

from libs import input_reading, constants

class EvaluationTask(dexen.Task):
    def __initialize__(self):
        self.boxes = input_reading.read_input()
        self.nboxes = len(self.boxes)
        self.iter = 0
        self.best_ind = None

    def __isinput__(self, ind):
        return (ind.phenotype != None and 
                ind.width == None and ind.height == None)    
    
    def __hasinput__(self):
        return True
    
    def __execute__(self, inds):
        self.iter += 1
        print "I am in evaluation", self.iter    
        self.evaluate_width(inds)
        self.evaluate_height(inds)
        for ind in inds:
            ind.area = ind.width * ind.height
            self.is_best(ind)
        if self.iter % 10 == 0: 
            print "At iter:", self.iter, "The best ind: ", self.best_ind
        return inds

    def is_best(self, ind):  
        if (self.best_ind == None or ind.area < self.best_ind.area):
            self.best_ind = copy.deepcopy(ind)
    
    def evaluate_individual_width(self, ind):
        phenotype = ind.phenotype
        genotype = ind.genotype 
        orient = genotype["orient"]
        max_found = 0
        side = 0
        for i in range(self.nboxes):
            if orient[i] == 0:
                side = self.boxes[i]['w']
            else:
                side = self.boxes[i]['h']
            if phenotype[i]['x'] + side > max_found:
                max_found = phenotype[i]['x'] + side
        ind.width = float(max_found)
    
    def evaluate_width(self, inds):
        for ind in inds:
            self.evaluate_individual_width(ind)
    
    def evaluate_individual_height(self, ind):
        phenotype = ind.phenotype
        genotype = ind.genotype 
        orient = genotype["orient"]
        max_found = 0
        side = 0
        for i in range(self.nboxes):
            if orient[i] == 0:
                side = self.boxes[i]['h']
            else:
                side = self.boxes[i]['w']
            if phenotype[i]['y'] + side > max_found:
                max_found = phenotype[i]['y'] + side
        ind.height = float(max_found)
                    
    def evaluate_height(self, inds):
        for ind in inds:
            self.evaluate_individual_height(ind)


